<script setup>
import { reactive, onMounted } from 'vue';
import axios from 'axios';

const config = reactive({
  header: ['时间', '含水率', '土壤温度', '含氮量', '空气温度', 'CO₂'],
  data: [],
  index: true,
  columnWidth: [150, 150, 150, 150, 150, 150, 150], // 根据需要调整列宽
  align: ['center', 'center', 'center', 'center', 'center', 'center'],
  headerBGC: '#003366',
});

const fetchData = async () => {
  try {
    // 假设所有数据都使用相同的时间戳，这里只获取一次时间数据
    const airTempResponse = await axios.get('http://localhost:8085/AirTemperature/tenAirTemperaturedata');
    const airTempData = airTempResponse.data;

    const timeData = airTempData.map(item => formatDateTime(item.createTime));

    // 获取其他数据
    const soilWaterData = (await axios.get('http://localhost:8085/SoilWater/tenSoilWaterdata')).data;
    const soilTempData = (await axios.get('http://localhost:8085/SoilTemperature/tenSoilTemperaturedata')).data;
    const soilNData = (await axios.get('http://localhost:8085/SoilN/tenSoilNdata')).data;
    const co2Data = (await axios.get('http://localhost:8085/CO2/tenCO2data')).data;

    // 假设所有数据数组长度相同，按索引合并数据
    const combinedData = timeData.map((_, index) => [
      timeData[index],
      soilWaterData[index].dataValue,
      soilTempData[index].dataValue,
      soilNData[index].dataValue,
      (airTempData[index].dataValue / 10),
      co2Data[index].dataValue,
    ]);

    config.data = combinedData;
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 格式化时间戳为 MM-DD HH:mm 的形式
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${month}-${day} ${hours}:${minutes}`;
};

onMounted(fetchData);

const mouseoverHandler = (e) => {
  console.log(e);
};

const clickHandler = (e) => {
  console.log(e);
};
</script>

<template>
  <div style="width:100%; height:100%; padding: 5px; box-sizing: border-box;">
    <dv-scroll-board
        :config="config"
        style="width:100%; height:100%"
        @mouseover="mouseoverHandler"
        @click="clickHandler"
    />
  </div>
</template>

<style scoped>

</style>